<?php
defined('SECUR_CHECK') or die("Security error");
/*
 *
 * Array validation class
 */
class validator
{
    var $rules;
    var $errors;
    
    function  __construct() {
        $this->rules = array();
        $this->errors = array();
    }
    /*
     * Set the rules for later validation
     */
    function  set_rules($rules_array)
    {
        $this->rules = array_merge($this->rules, $rules_array);
    }
    /*
     * The actual validation
     */
    function validate($validate_array)
    {
        $validated = TRUE;
        foreach($this->rules as $rule)
        {
            if(isset($validate_array[$rule['name']]))
            {
                //Variable is set in array, check for validation
                if(isset($rule['regexp'])) // Regular expression validation
                {
                    if(preg_match($rule['regexp'], $validate_array[$rule['name']]) == 0)
                    {
                        $validated = FALSE;
                        $this->errors[] = "{$rule['label']} is unvalid";
                    }
                }
                if(isset($rule['matches'])) // Exact matches validation
                {
                    if(!in_array($validate_array[$rule['name']], $rule['matches']))
                    {
                        $validated = FALSE;
                        $this->errors[] = "{$rule['label']} does not match valid values";
                    }
                }
            }
            else
            {
                // Variable isnt set, so not validated
                $validated = FALSE;
                $this->errors[] = "{$rule['label']} is not set";
            }
        }
        return $validated;
    }
}